import {ref, Ref} from 'vue';
import {Loading, pageLoading} from '@/model/LoadingClass';
class LoadingMap {
  private loadingMap!: Map<symbol, Ref<boolean>>;
  constructor() {
    this.loadingMap = new Map<symbol, Ref<boolean>>();
  }
  public getLoadingValue(name: symbol | undefined): Ref<boolean> | undefined {
    if (name === undefined) {
      return undefined;
    } else {
      return this.loadingMap.get(name);
    }
  }
  public setLoadingValue(name: symbol, value: boolean): void {
    const res = this.loadingMap.get(name);
    if (res !== undefined) {
      res.value = value;
    } else {
      this.loadingMap.set(name, ref(value));
    }
  }
  public setAndGetLoadingValue(name: symbol, value: boolean): Ref<boolean> {
    const res = this.loadingMap.get(name);
    if (res !== undefined) {
      res.value = value;
      return res;
    } else {
      const refValue = ref(value);
      this.loadingMap.set(name, refValue);
      return refValue;
    }
  }
  public deleteValue(name: symbol): void {
    this.loadingMap.delete(name);
  }

  public clearMap(): void {
    this.loadingMap.clear();
  }
}

class LoadingUtil {
  public startLoading(loadingEnv?: Loading | Ref<boolean> | undefined): void {
    if (loadingEnv !== undefined && loadingEnv !== null) {
      loadingEnv.value = true;
    } else {
      pageLoading.openPageLoading();
    }
  }
  public endLoading(loadingEnv?: Loading | Ref<boolean> | undefined): void {
    if (loadingEnv !== undefined && loadingEnv !== null) {
      loadingEnv.value = false;
    } else {
      pageLoading.closePageLoading();
    }
  }
}


export let loadingUtil = new LoadingUtil();
